package com.hwtx.form.domain;

import com.hwtx.form.domain.repo.I18nRepo;
import com.hwtx.form.persistence.entity.I18nMessage;
import jakarta.annotation.Resource;
import org.jetbrains.annotations.NotNull;
import org.springframework.context.support.AbstractMessageSource;

import java.text.MessageFormat;
import java.util.Locale;
import java.util.Objects;

public class DbMessageSource extends AbstractMessageSource {
    @Resource
    private I18nRepo i18nRepo;

    @Override
    protected MessageFormat resolveCode(@NotNull String code, @NotNull Locale locale) {
        String msg = getMessageFromDatabase(code, locale);
        if (msg == null) {
            return null;
        }
        return createMessageFormat(msg, locale);
    }

    @Override
    protected String resolveCodeWithoutArguments(@NotNull String code, @NotNull Locale locale) {
        return getMessageFromDatabase(code, locale);
    }

    public String getMessageFromDatabase(String code, Locale locale) {
        I18nMessage message = i18nRepo.getI18nMessage(code);
        if (message == null) {
            // 如果数据库中找不到，返回默认消息或抛出异常
            return getDefaultMessage(code);
        }
        if (Objects.equals(locale.getLanguage(), "zh")) {
            return message.getZh();
        } else if (Objects.equals(locale.getLanguage(), "en")) {
            return message.getEn();
        }
        return null;
    }
}